package com.dhecp.project.storage.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.dto.IndexConfigDto;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.storage.domain.DeliveryBox;
import com.dhecp.project.storage.domain.DeliveryBoxDetail;
import com.dhecp.project.storage.enums.DeliveryBoxEnum;
import com.dhecp.project.storage.service.DeliveryBoxDetailService;
import com.dhecp.project.storage.service.DeliveryBoxService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 海外仓 控制层
 */
@Controller
@RequestMapping("/storage/deliveryBox")
public class HWDeliveryBoxController extends BaseModuleController {

    private String prefix = "storage/deliveryBox";
    private String moduleTable = ModuleTable.DELIVERY_BOX;
    private String moduleTable2 = ModuleTable.DELIVERY_BOX_DETAIL;

    @Autowired
    private DeliveryBoxService deliveryBoxService;
    @Autowired
    private DeliveryBoxDetailService deliveryBoxDetailService;
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;
    @Autowired
    private SysDictionaryForFieldService sysDictionaryForFieldService;

    /**
     * @Description: 打开查询列表页
     */
    @RequiresPermissions("storage:deliveryBox:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryBox()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/deliveryBox"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "deliveryBox");
        return mv;
    }

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryBox:view")
    @GetMapping("/indexConfig")
    @ResponseBody
    public AjaxResult indexConfig(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryBox()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
    	
        IndexConfigDto dto = this.getIndexConfig(params);
        AjaxResult ajaxResult = AjaxResult.success(dto);
        return ajaxResult;
    }

    /**
     * @Description: 查询页 列表数据
     */
    @RequiresPermissions("storage:deliveryBox:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<DeliveryBox> list = new ArrayList<DeliveryBox>();
        try {
            params.put("stateName", DeliveryBoxEnum.StateName.INIT.value);
            list = deliveryBoxService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryBox:view")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(String bid) {
    	
    	
    	
    	System.out.println("bid---" + bid);
        try {

        	Map<String, Object> params = new HashMap<String, Object>();
            params.put("moduleTable", moduleTable2);
            params.put("entity", new DeliveryBoxDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("toolBarWidth", 0);
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("sonList", deliveryBoxDetailService.listByBidBox(bid));
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            AjaxResult ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }


    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     */
    @RequiresPermissions("storage:deliveryBox:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryBox()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/deliveryBox_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:deliveryBox:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }
        
        String bid = params.get("bid").toString();

        try {
            Map<String, Object> headData = new HashMap<String, Object>();        //表头的业务数据
            DeliveryBox businessData = deliveryBoxService.queryByBid(bid);
            if (businessData == null) { //未查询到对应单据，页面初始化值
                ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                DeliveryBox deliveryBox = new DeliveryBox();
                deliveryBox.setBid(moduleNidAndBid.getBid());
                deliveryBox.setCreateTime(new Date());

                headData = TypeUtils.entityToMap(deliveryBox);
            } else {
                headData = TypeUtils.entityToMap(businessData);
            }
            params.put("headData", headData); //表头的业务数据

            ModelAndView mv = this.openEditPage(params);

            String bidBox = businessData.getBid();
            List<DeliveryBoxDetail> listDeliveryBoxDetail = deliveryBoxDetailService.listByBidBox(bidBox);
            mv.addObject("detailList", listDeliveryBoxDetail);//明细数据

            return mv;
        } catch (Exception e) {
        	e.printStackTrace();
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * 保存
     */
    @RequiresPermissions("storage:deliveryBox:edit")
    @Log(title = "保存海外仓发货装箱单单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //System.out.println("params"+params);
            ajaxResult = deliveryBoxService.saveData(params);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 导出
     */
    @RequiresPermissions("storage:deliveryBox:export")
    @Log(title = "海外仓发货装箱数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryBox());

        List<DeliveryBox> list = deliveryBoxService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = sysDictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<DeliveryBox> util = new ExportExcelUtils<DeliveryBox>(moduleTable, new DeliveryBox());
        return util.exportExcel(list, fieldList, "海外仓发货装箱数据", "export");
    }

    /**
     * 审核
     */
    //@RequiresPermissions("storage:deliveryBox:updateState")
    @Log(title = "海外仓发货装箱审核", businessType = BusinessType.UPDATE)
    @PostMapping("/updateState")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateState(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryBoxService.updateState(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 回退
     */
    //@RequiresPermissions("storage:deliveryBox:refuse")
    @Log(title = "海外仓发货装箱回退", businessType = BusinessType.UPDATE)
    @PostMapping("/refuse")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult refuse(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryBoxService.refuse(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}